package org.example.servlet;

import org.example.dao.UserDao;
import org.example.exception.AppException;
import org.example.model.User;
import org.example.util.Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;  //注解是干什么的呢？奥力给干
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        User user = new User();

        //1.解析请求数据，根据接口文档需使用反序列化操作
        User user1 = Util.deserialize(req.getInputStream(),User.class); 

        //2.业务逻辑处理
        try{
            if(user1.getName() == null || user1.getName().equals("")){
                throw new AppException("用户名输入为空，请重新输入！");
            }
            if(user1.getPassword() == null || user1.getPassword().equals("")){
                throw new AppException("密码输入为空，请重新输入！");
            }
            if(user1.getNickName() == null || user1.getNickName().equals("")){
                throw new AppException("昵称输入为空，请重新输入！");
            }
            if(user1.getSignature() == null || user1.getSignature().equals("")){
                throw new AppException("个人特点输入为空，请重新输入！");
            }
            int num = UserDao.insertUser(user1);  //将反序列化后的对象插入数据库
            user = user1;
            user.setOk(true);
        }catch(Exception e){
            e.printStackTrace();
            //构造错误信息：ok-false reason-错误信息
            user.setOk(false);
            //抛出自定义异常给用户看，直观清晰
            if(e instanceof AppException){
                user.setReason(e.getMessage());
            }else{
                user.setReason("未知的错误，非常抱歉！请联系管理者");
            }
        }

        //3.将响应的数据返回：根据响应对象获取输出流，将输出响应放在response报文body中
        resp.getWriter().println(Util.serialize(user)); //将对象序列化为json字符串输出到前面界面
    }
}
